package com.haredot.controller;

import com.haredot.dto.BindSysMenuDto;
import com.haredot.entity.Sys;
import com.haredot.service.SystemService;
import com.haredot.utils.ValidUtils;
import com.haredot.validation.Insert;
import com.haredot.vo.R;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;


@RestController
@RequestMapping("/sys")
public class SystemController {

    @Resource
    private SystemService systemService ;

    @PostMapping("/add")
    @PreAuthorize("hasAuthority('sys:add')")
    public R<?> addSys(@RequestBody @Validated(Insert.class) Sys sys, BindingResult bindingResult) {

        return ValidUtils.toResult(bindingResult, ()-> {
            // 组装时间参数
            sys.setCreateTime(LocalDateTime.now());
            return systemService.saveSys(sys);
        }) ;
    }

    @PutMapping("/update/{id}")
    @PreAuthorize("hasAuthority('sys:update')")
    public R<?> updateSys(@PathVariable("id") Long id,
                          @RequestBody @Validated Sys sys,
                          BindingResult bindingResult) {

        return ValidUtils.toResult(bindingResult, ()-> {
            // 组装时间参数
            sys.setUpdateTime(LocalDateTime.now());
            sys.setId(id);
            return systemService.updateSys(sys);
        }) ;
    }

    @GetMapping("/check/{sysName}")
    public R<?> checkSysName(@PathVariable("sysName") String sysName) {

        return systemService.checkSys(sysName);
    }

    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys')")
    public R<Sys> list() {

        return systemService.queryAllSys();
    }

    @DeleteMapping("/del/{id}")
    @PreAuthorize("hasAuthority('sys:delete')")
    public R<?> delSys(@PathVariable("id") Long id) {
        return systemService.removeSys(id);
    }

    @DeleteMapping("/batch")
    @PreAuthorize("hasAuthority('sys:batch:del')")
    public R<?> batchDelSys(@RequestBody List<Long> ids) {
        return systemService.removeSys(ids);
    }


    @GetMapping("/menuBindSysList/{menuId}")
    @PreAuthorize("hasAnyAuthority('sys:bind:menu', 'sys:add', 'sys:update')")
    public R<BindSysMenuDto> menuBindSysList(@PathVariable("menuId") Long menuId) {
        return systemService.queryMenuBindSysList(menuId);
    }

    @PutMapping("/bindMenu/{sysId}")
    @PreAuthorize("hasAuthority('sys:bind:menu')")
    public R<?> bindMenu(@PathVariable("sysId") Long sysId, @RequestBody List<Long> menuIds) {

        return systemService.bindMenu(sysId, menuIds);
    }
}
